﻿using AutoMapper;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using WMS.FC.Domain.DomainObject.System;
using WMS.FC.Domain.Repository;
using WMS.FC.Domain.Service.System.Interface;

namespace WMS.FC.Domain.Service.System
{
    public class GetPageDataService : ServiceBase, IGetPageDataService
    {
        protected readonly ISystemRepository systemRepository;
        protected readonly IMenuRepository menuRepository;

        public GetPageDataService(
            ILogger<ServiceBase> logger,
            IOptions<WmsSettings> options,
            IMapper mapper,
            ISystemRepository systemRepository,
            IMenuRepository menuRepository)
            : base(logger, options, mapper)
        {
            this.systemRepository = systemRepository;
            this.menuRepository = menuRepository;
        }

        public async Task<ActionResult<PageDataDO>> GetPageData(string menuId, Dictionary<string, object>? parameters, Pagination? pagination, Sorter? sorter, UserInfo userInfo)
        {
            var result = new ActionResult<PageDataDO>("获取页面数据");
            try
            {
                if (string.IsNullOrWhiteSpace(menuId))
                    return result.ArgumentError("菜单ID不能为空");

                var menuPO = await menuRepository.GetMenu(Convert.ToInt64(menuId));
                if (menuPO == null)
                    return result.DbError($"ID:{menuId},菜单数据未找到");

                var sql = menuPO.Sql;
                if (string.IsNullOrWhiteSpace(sql))
                    return result.BusinessError($"菜单:{menuPO.NameCN},未设置查询Sql");

                var rowCount = await systemRepository.ExecuteQueryCount(sql, parameters, userInfo);
                var table = await systemRepository.ExecuteQuery(sql, parameters, pagination, sorter, userInfo);

                result.Data = new PageDataDO()
                {
                    Total = rowCount,
                    Rows = table
                };
            }
            catch (Exception ex)
            {
                return result.Exception(ex);
            }

            return result;
        }
    }
}
